package com.bwie.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.unit.R;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public R login(@RequestBody User user){
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername,user.getUsername());
        User userLogin = userService.getOne(wrapper);
        if (userLogin == null){
            return R.ERROR(500,"账号错误");
        }

        String bcrypt = DigestUtil.bcrypt(user.getPassword());
        System.out.println("加密后的密码是"+bcrypt);
        boolean b = DigestUtil.bcryptCheck(user.getPassword(), userLogin.getPassword());
        if (!b){
            return R.ERROR(500,"密码错误");
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("id",userLogin.getId());
        String token = Jwts.builder().setClaims(map).signWith(SignatureAlgorithm.HS256, "bwie".getBytes()).compact();
        map.put("token",token);
        return R.OK(map);
    }

}
